using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class CompanyWizard : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["mn"] != null)
        {
            if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
            {
                tblDynamicMain.Visible = false;
                trbtn.Visible = false;
                trstar.Visible = false;
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                return;
            }
        }

        hdds.logMenuClick(Request.QueryString["mn"].ToString());
        manageLogoUpload();
        getpageicons(); // Added by srivatsan for icon display
        if (Page.IsPostBack == false)
        {
            loadOwneridDropDown();
            loadLocales();
            LoadCompany();            
        }
        EmailFieldShow(); // Added by srivatsan
    }
    private void manageLogoUpload()
    {
        if (IsPostBack) return;
        HDDatabase hdd = null;
        DynamicDisplayI ddi = null;
        try
        {
            hdd = new HDDatabase();
            DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where af_row_id='994bbfc8cbab4da5'");
            hdd = null;
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["mem_value1"].ToString().ToLower() == "true" || dt.Rows[0]["mem_value1"].ToString() == "1")
                    {
                        //check later for enabbling if needed
                    }
                    else
                    {
                        FileUploadLogo.Enabled = false;
                        ddi = new DynamicDisplayI();
                        HtmlTableRow htr = (HtmlTableRow)ddi.FindControl(this.Controls, "trLogo");
                        htr.Style.Add("display", "none");
                    }
                }
            }

        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageLogoUpload. " + e.Message);
        }
        finally
        {
            hdd = null;
            ddi = null;
        }
    }
    private void loadLocales()
    {
        DataTable dt = new DataTable();
        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
        ddLocale.Items.Clear();
        try
        {
            
            dt = hdd.GetDataTable("Select locale_id,locale_name,is_default from sy_locales where is_neutral=0");
            ddLocale.DataSource = dt;
            ddLocale.DataTextField = "locale_name";
            ddLocale.DataValueField = "locale_id";
            ddLocale.DataBind();
            DataRow[] dr = dt.Select("is_default = 'true'");
            if (dr.Length > 0)
                ddLocale.Items.FindByValue(dr[0]["locale_id"].ToString()).Selected = true;
            #region Old code commented by 'Imran Gani' on 28-Feb-2014, for simple code
            //string temp = "";
            //if (dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        if (dr["is_default"].ToString().ToLower() == "true") temp = dr["locale_id"].ToString();
            //        ddLocale.Items.Add(new ListItem(dr["locale_name"].ToString(), dr["locale_id"].ToString()));
            //    }                
            //}
            //if (temp.Length>0)
            //{
            //    ddLocale.Items.FindByValue(temp).Selected = true;
            //}
            #endregion
        }
        catch (Exception e)
        {
//            lbl_message.Text = e.Message;
            LogWriter.WriteLog("Error in loadLocales. " + e.Message);
        }
        finally
        {
            hdd = null;
            dt = null;
        } 
    }
    private void LoadCompany()
    {
        DataTable dt = new DataTable();
        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());

        try 
        {
            dt = hdd.GetDataTable("Select * from ngcompany where company_id = '" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "'");
            if (dt.Rows.Count > 0)
            {
                //function added by Sampath on 17-Nov-2011 for IPP Tech check 
                //CommonFunctions.decodeData(dt);

                tb_company_id.Text = dt.Rows[0]["company_id"].ToString();
                tb_company_name.Text = dt.Rows[0]["company_name"].ToString();
                tb_add1.Text = dt.Rows[0]["Address1"].ToString();
                tb_add2.Text = dt.Rows[0]["Address2"].ToString();
                tb_city.Text = dt.Rows[0]["city"].ToString();
                tb_state.Text = dt.Rows[0]["state"].ToString();
                tb_pincode.Text = dt.Rows[0]["pincode"].ToString();
                tb_email.Text = dt.Rows[0]["email"].ToString();
                tb_phone.Text = dt.Rows[0]["phone"].ToString();
                tb_fax.Text = dt.Rows[0]["fax"].ToString();
                lnkDeleteLogo.Visible = dt.Rows[0]["logo_content"] != System.DBNull.Value;
                if (lnkDeleteLogo.Visible)
                {
                    lnkDeleteLogo.ToolTip = "Delete the existing logo file (" + dt.Rows[0]["logo_file_name"].ToString() + ")";
                }
                HF_af_row_id.Value = dt.Rows[0]["af_row_id"].ToString();
                HF_created_by.Value = dt.Rows[0]["created_by"].ToString();
                HF_owner_id.Value = dt.Rows[0]["owner_id"].ToString(); // Added by srivatsan on June 15 2009 for owner id field
                ddownerid.SelectedValue = dt.Rows[0]["owner_id"].ToString();
                Hf_created_date.Value = dt.Rows[0]["created_date"].ToString();
                if (dt.Rows[0]["default_locale"].ToString().Length>0)
                    ddLocale.SelectedValue = dt.Rows[0]["default_locale"].ToString();
            }
        }
        catch (Exception e)
        {
            lbl_message.Text = wrapItAsMessage(e.Message,true);  
        }
        finally 
        {
            hdd = null;
            dt = null;
        } 
    }

    private bool SaveCompany()
    {
        HDDatabase hdd;
        SqlConnection sc = null;
        SqlCommand scom;

        try
            {
                hdd = new HDDatabase();
                sc = hdd.GetConnection("servercon");
                //function added by Sampath on 17-Nov-2011 for IPP Tech check 
                
                //scom = new SqlCommand("update ngcompany set company_name = '" + tb_company_name.Text.Replace("'", "''") + "',Address1 = '" + tb_add1.Text.Replace("'", "''") + "',Address2 = '" + tb_add2.Text.Replace("'", "''") + "',city = '" + tb_city.Text.Replace("'", "''") + "',state = '" + tb_state.Text.Replace("'", "''") + "',pincode = '" + tb_pincode.Text.Replace("'", "''") + "',email = '" + tb_email.Text.Replace("'", "''") + "',phone = '" + tb_phone.Text.Replace("'", "''") + "',fax = '" + tb_fax.Text.Replace("'", "''") + "',created_date = '" + Hf_created_date.Value.Replace("'", "''") + "',modified_date = '" + DateTime.Now.ToString() + "',af_row_id = '" + HF_af_row_id.Value.Replace("'", "''") + "',created_by = '" + HF_created_by.Value.Replace("'", "''") + "',modified_by = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "',default_locale = '" + ddLocale.SelectedValue + "' where company_id='" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "'");
                scom = new SqlCommand("update ngcompany set company_name = '" + tb_company_name.Text.Replace("'", "''") + "',Address1 = '" + tb_add1.Text.Replace("'", "''") + "',Address2 = '" + tb_add2.Text.Replace("'", "''") + "',city = '" + tb_city.Text.Replace("'", "''") + "',state = '" + tb_state.Text.Replace("'", "''") + "',pincode = '" + tb_pincode.Text.Replace("'", "''") + "',email = '" + tb_email.Text.Replace("'", "''") + "',phone = '" + tb_phone.Text.Replace("'", "''") + "',fax = '" + tb_fax.Text.Replace("'", "''") + "',created_date = '" + Hf_created_date.Value.Replace("'", "''") + "',modified_date = '" + DateTime.Now.ToString() + "',af_row_id = '" + HF_af_row_id.Value.Replace("'", "''") + "',created_by = '" + HF_created_by.Value.Replace("'", "''") + "',owner_id='" + ddownerid.SelectedValue + "',modified_by = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "',default_locale = '" + ddLocale.SelectedValue + "' where company_id='" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "'");// Added by srivatsan on June 15 2009 for owner id field
                scom.Connection = sc;
                scom.Connection.Open();
                int records = scom.ExecuteNonQuery();
                //scom.Connection.Close();
            }
            catch (Exception e)
            {
                lbl_message.Text = wrapItAsMessage(e.Message,true);  
                return false;
            }
            finally
            {

                sc.Close();
                sc = null;
                scom = null;
                hdd = null;
            }

            return true;
    }
    private string uploadFile(bool updateMode)
    {
        try
        {
            if (FileUploadLogo.HasFile)
            {
                if (FileUploadLogo.FileName.Length > 0)
                {
                    int len = FileUploadLogo.PostedFile.ContentLength;
                    //if (len > 5242880) return "Exceeded the file size limit.";
                    if (len > 4096000) return "Exceeded the file size limit.";
                    byte[] filea = new byte[len];
                    FileUploadLogo.PostedFile.InputStream.Read(filea, 0, len);
                    string sql = "update ngcompany set logo_content=@pcont, logo_file_name='" + System.IO.Path.GetFileName(FileUploadLogo.PostedFile.FileName).Replace("'", "''")
                                    + "' where company_id='" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "'";

                    SqlCommand sc = new SqlCommand(sql);
                    SqlParameter sp = new SqlParameter("@pcont", SqlDbType.VarBinary, len);
                    FileUploadLogo.PostedFile.InputStream.Close();
                    sp.Value = filea;
                    sc.Parameters.Add(sp);
                    HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
                    hdd.ExecuteCmdObj(sc);
                    hdd = null;
                }
                return "";
            }
            return "";
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
    private bool ValidateCompany(ref string message)
    {
        return validFile(ref message);
    }
    private bool validFile(ref string message)
    {
        if (FileUploadLogo.HasFile)
        {
            string ext = System.IO.Path.GetExtension(FileUploadLogo.PostedFile.FileName).ToLower();
            string[] invalids = new string[] { ".jpg", ".jpeg", ".bmp", ".gif", ".png" };
            for (int i = 0; i < invalids.Length; i++)
            {
                if (ext.IndexOf(invalids[i]) > -1)
                {
                    //check for image size
                    //Image im = new Image();
                    //System.Drawing.Image.
                    return true;
                }
            }
            message = "&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Invalid Image.";
            return false;
        }
        else
            return true;
    }
    protected void btn_save_Click(object sender, EventArgs e)
    {
        string message = "";
        if (!ValidateCompany(ref message))
        {
            lbl_message.Text = wrapItAsMessage(message,true);
            return;
        }
        if (SaveCompany())
        {
            if (uploadFile(false) == "")
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/tick4.gif' border='0'>&nbsp;Company details saved. ",false); //changed by prithi on 06-Aug-2008 
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Unable to save the company details. ",true);
            }
        }
        else
        {
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Unable to save the company details.",true);
        }
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    private void getpageicons() // added by srivatsan for icon display
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            string strPagesetRowId = HDD.GetColumnValue("sy_mnu", "pageset_id", "af_row_id='" + Request.QueryString["mn"].ToString() + "'");
            imgliteral.Text = icons.geticontextfrompageset(strPagesetRowId, 2).ToString();
            
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons()" + ex.Message);
            imgliteral.Text = "<img src=" + PageIcons.strdefaulticon.ToString() + "></img>";
        }
        finally
        {
            HDD = null;
            icons = null;
        }
    }
    protected void lnkDeleteLogo_Click(object sender, EventArgs e)
    {
        HDDatabase hdd = null;
        try
        {
            hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            int ret = hdd.ExecuteCmdObj(new SqlCommand("update ngcompany set logo_content=null, logo_file_name=null where company_id='" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "'"));
            if (ret>0)
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/tick4.gif' border='0'>&nbsp;Current logo deleted. Re-login to apply the changes.",false);
                lnkDeleteLogo.Visible = false;
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Unable to delete the existing logo.",true);
            }
            hdd = null;
        }
        catch (Exception ee)
        {
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Unable to delete the existing logo.",true);
        }
        finally
        {
            hdd = null;
        }
    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {
            string strBindRowID = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
            BC.Bind(strBindRowID,ddownerid, ref dt,null);

            if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
            {
                if (ddownerid.Items.FindByValue("e51e0327224a2eb9") == null)
                {
                    ddownerid.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
                }
            }
            else
            {
                ddownerid.Items.Remove(ddownerid.Items.FindByValue("e51e0327224a2eb9"));
            }

            //if (Request.QueryString["PK"] == null)
            //{
            //    ddownerid.SelectedValue = Session["user_afrowid"].ToString();
            //}
            //if (Request.QueryString["PK"] != null)
            //{
            //    if (Request.QueryString["CPY"] != null)
            //    {
            //        ddownerid.SelectedValue = Session["user_afrowid"].ToString();
            //    }

            //}

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }
    private void EmailFieldShow()
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sql = "select mem_value1 from sy_acr_mem where af_row_id = 'cf8a4613c5ea8a01'";
            string value = HDD.GetColumnValue(sql);
            if (value.Trim() != "")
            {
                if(Convert.ToBoolean(value.Trim()))
                {
                    tb_email.Enabled = true;
                }
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : EmailFieldShow :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }
}
